<template>
  <div class="scan-login">
    <h2>PC 扫码登录</h2>
    <div id="qrcode-container">
      <canvas id="qrcode"></canvas>
    </div>
    <p v-if="data.status === 'waiting'">请使用手机扫描二维码登录</p>
    <p v-if="data.status === 'logged_in'">登录成功，正在跳转...</p>
    <p v-if="data.status === 'expired'">二维码已过期，请刷新重试</p>
    <button v-if="data.status === 'expired'" @click="generateQRCode">重新生成二维码</button>
  </div>
</template>



<script setup>
import QRCode from "qrcode"; // 引入二维码库
import axios from "axios"; // 引入 axios 处理网络请求
import { reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const data = reactive({
  token: "", // 后端生成的唯一标识
  status: "waiting", // 登录状态：waiting, logged_in, expired
  pollingInterval: null, // 轮询计时器
})

// 生成二维码
const generateQRCode = async () => {
  try {
    // 获取 Token
    const response = await axios.get("http://localhost:3100/api/login/get-token");
    data.token = response.data.token;
    // 生成二维码
    const qrCodeData = `https://your-backend.com/scan-login?token=${data.token}`;
    const qrcodeCanvas = document.getElementById("qrcode");
    await QRCode.toCanvas(qrcodeCanvas, qrCodeData, {
      width: 200,
    });
    // 开始轮询登录状态
    startPolling()
  } catch (error) {
    console.error("生成二维码失败:", error);
  }
}

// 开始轮询登录状态
const startPolling = () => {
  if (data.pollingInterval) {
    clearInterval(data.pollingInterval);
  }
  data.pollingInterval = setInterval(async () => {
    try {
      const response = await axios.get(
        `http://localhost:3100/api/login/check-status?token=${data.token}`
      );
      data.status = response.data.status;

      if (data.status === "logged_in") {
        clearInterval(data.pollingInterval); // 停止轮询
        redirectToDashboard();
      } else if (data.status === "expired") {
        clearInterval(data.pollingInterval); // 停止轮询
      }
    } catch (error) {
      console.error("轮询登录状态失败:", error);
    }
  }, 2000);// 每 2 秒轮询一次
}

const redirectToDashboard = () => {
  setTimeout(() => {
    router.push('/home')
  }, 1000); // 延迟 1 秒
}

onMounted(() => {
  generateQRCode()
})

onUnmounted(() => {
  if (data.pollingInterval) {
    clearInterval(data.pollingInterval)
  }
})

</script>


<style scoped>
.scan-login {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

#qrcode-container {
  margin: 20px 0;
}
</style>
